package com.jerry.controller;

import com.jerry.config.VideoConfig;
import com.jerry.response.CommonResponse;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;


@RestController
@RequestMapping("/video")
public class VideoController {
    private final VideoConfig videoConfig;

    public VideoController(VideoConfig videoConfig) {
        this.videoConfig = videoConfig;
    }

    @GetMapping("/{fileName}")
    public ResponseEntity<Resource> play(@PathVariable String fileName) {
        String videoFilePath = videoConfig.getWorkSpace() + fileName;
        Path path = Paths.get(videoFilePath);
        Resource resource = new FileSystemResource(path.toFile());
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=\"" + resource.getFilename() + "\"");
        // 使用APPLICATION_OCTET_STREAM作为通用二进制流类型
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 创建响应实体并返回
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }
    @PostMapping("/upload")
    public CommonResponse<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + suffix;
        String basepath = videoConfig.getImgSpace();
        File dir = new File(basepath);
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            file.transferTo(new File(basepath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResponse.success();
    }
}
